package com.xiangxiao.rpan.utils;
import cn.hutool.core.util.StrUtil;
import com.xiangxiao.rpan.utils.constant.GlobalConsts;

import cn.hutool.core.io.FileUtil;
import com.xiangxiao.rpan.utils.constant.ResponseCode;
import com.xiangxiao.rpan.utils.exception.UtilsExcetion;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Http工具类
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2022/12/29 16:10
 */
public class HttpUtil {
  /**
   * 添加跨域的响应头
   *
   * @param response
   */
  public static void addCorsResponseHeader(HttpServletResponse response) {
    response.setHeader(CorsConfigEnum.CORS_ORIGIN.getKey(), CorsConfigEnum.CORS_ORIGIN.getValue());
    response.setHeader(CorsConfigEnum.CORS_CREDENTIALS.getKey(), CorsConfigEnum.CORS_CREDENTIALS.getValue());
    response.setHeader(CorsConfigEnum.CORS_METHODS.getKey(), CorsConfigEnum.CORS_METHODS.getValue());
    response.setHeader(CorsConfigEnum.CORS_MAX_AGE.getKey(), CorsConfigEnum.CORS_MAX_AGE.getValue());
    response.setHeader(CorsConfigEnum.CORS_HEADERS.getKey(), CorsConfigEnum.CORS_HEADERS.getValue());
  }

  /**
   * 跨域设置枚举类
   */
  public enum CorsConfigEnum {
    /**
     * 允许所有远程访问
     */
    CORS_ORIGIN("Access-Control-Allow-Origin", "*"),
    /**
     * 允许认证
     */
    CORS_CREDENTIALS("Access-Control-Allow-Credentials", "true"),
    /**
     * 允许远程调用的请求类型
     */
    CORS_METHODS("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT"),
    /**
     * 指定本次预检请求的有效期，单位是秒
     */
    CORS_MAX_AGE("Access-Control-Max-Age", "3600"),
    /**
     * 允许所有请求头
     */
    CORS_HEADERS("Access-Control-Allow-Headers", "*");

    CorsConfigEnum(String key, String value) {
      this.key = key;
      this.value = value;
    }

    private String key;
    private String value;

    public String getKey() {
      return key;
    }

    public String getValue() {
      return value;
    }
  }

  /**
   * 获取远程文件大小
   * @param   url 文件 URL
   * @return  文件大小
   */
  public static Long getRemoteFileSize(String url) {
    long size = 0;
    URL urlObject;
    try {
      urlObject = new URL(url);
      URLConnection conn = urlObject.openConnection();
      size = conn.getContentLength();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return size;
  }

  /**
   * 获取 URL 对应的文件内容
   * @param   url 文件 URL
   * @return  文件内容
   */
  public static String getTextContent(String url) {
    long maxFileSize = 1024 * GlobalConsts.TEXT_MAX_FILE_SIZE_KB;

    if (getRemoteFileSize(url) > maxFileSize) {
      throw new UtilsExcetion("预览文件超出大小, 最大支持 " + FileUtil.readableFileSize(maxFileSize), ResponseCode.FAIL);
    }

    String result;
    try {
      result = cn.hutool.http.HttpUtil.get(url);
    } catch (Exception e) {
      e.printStackTrace();
      throw new UtilsExcetion(StrUtil.format("获取文件内容失败, URL: {}", url), ResponseCode.FAIL);
    }

    return result == null ? "" : result;
  }
}
